<template>
  <div class="app-container calendar-list-container">
    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="数据加载中，请稍后" border fit highlight-current-row :default-sort="{prop: 'inTime', order: 'descending'}" @sort-change="getSortList" style="width: 100%">
      <el-table-column align="center" label="资讯标题" show-overflow-tooltip
       min-width="240">
          <template slot-scope="scope">
              {{scope.row.title}}
          </template>
      </el-table-column>
      <el-table-column align="center" label="状态">
          <template slot-scope="scope">
              {{scope.row.auditStatusDesc}}
          </template>
      </el-table-column>
      <el-table-column align="center" label="作者" show-overflow-tooltip>
          <template slot-scope="scope">
              {{scope.row.authorName}}
          </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" min-width="90">
          <template slot-scope="scope">
              {{scope.row.createTime | dateformat('YYYY-MM-DD HH:mm')}}
          </template>
      </el-table-column>
      <el-table-column align="center" label="更新时间" min-width="90">
          <template slot-scope="scope">
              {{scope.row.updateTime | dateformat('YYYY-MM-DD HH:mm')}}
          </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="90">
        <template scope="scope">
          <el-button size="small" @click="handleModifyStatus(scope.row)">编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNo" :page-sizes="[10,20,30,50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog top="4%" width="70%" title="编辑页" :visible.sync="dialogFormVisible" :before-close="handleClose">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="100px" style='width: 70%; margin-left:50px;'>
        <el-form-item label="标题" prop="title">
          <el-input type="textarea" maxlength="100" :autosize="{ minRows: 2, maxRows: 4}" v-model="temp.title"></el-input>
        </el-form-item>
        <el-form-item label-width="110px" label="栏目资讯：" class="postInfo-container-item" prop="brand" >
            <el-cascader
                change-on-select  placeholder="请选择" expand-trigger="click"
              :options="sections"
              v-model="sectionId"
            ></el-cascader>
        </el-form-item>
        <el-form-item label="设置标签：" class="postInfo-container-item" prop="nickname">
          <multiselect style="line-height:initial" v-model="labelsVal" :options="labels" @search-change="getInfoLabels" placeholder="搜索标签" selectLabel="选择" :multiple="true" deselectLabel="删除" track-by="id" :internalSearch="false" label="name">
            <span slot='noResult'>无搜索结果</span>
          </multiselect>
        </el-form-item>  
        <el-form-item label-width="110px" label="上传封面：" class="postInfo-container-item">
          <el-upload
            class="upload-demo"
            :headers="headers"
            drag
            action="/tools/oss/upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleUploadSuccess"
            list-type="picture"
            :file-list="fileList"
            :limit="2"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将图片拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-form-item>      
        <el-form-item label="内容" prop="content">
          <Tinymce :height=150 ref="editor" v-model="temp.content" :value="temp.content" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, delId, delIds, update, getId, getSectionCascade, getInfoLabels } from '@/api/advisory'
import { getToken } from '@/utils/auth' // 验权
import Tinymce from '@/components/Tinymce'
import Multiselect from 'vue-multiselect'; // 使用的一个多选框组件，element-ui的select不能满足所有需求
import 'vue-multiselect/dist/vue-multiselect.min.css'; // 多选框组件css
export default {
  name: 'list',
  components: { Tinymce , Multiselect},
  data() {
    return {
      labels:[],
      sections:[],
      sectionId:null,
      headers: {},
      inputVisible: false,
      inputValue: '',
      brandListOptions: [],
      labelsVal:[],
      fileList:[],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      date: '',
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        keyWord: '',
        labelId: null,
        pageNo: 1,
        pageSize: 10
      },
      temp: {},
      dialogFormVisible: false,
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        'section.name': [{ required: true, message: '所属栏目必填', trigger: 'blur' }],
        'section.tab': [{ required: true, message: '标签必填', trigger: 'blur' }],
        inTime: [{ type: 'date', required: true, message: '发布日期必填', trigger: 'change' }],
        view: [{ required: true, message: '阅读数必填', trigger: 'blur' }],
        platform: [{ required: true, message: '平台必填', trigger: 'blur' }]
      },
      tableKey: 0
    }
  },
  mounted() {
    this.getList()
    this.getSectionCascade()
    this.getInfoLabels('')
    this.headers = { accessToken: getToken() }
  },
  watch: {

  },
  methods: {
    handleClose() {    
      this.$confirm('数据未保存，确认关闭？').then(() => {
        // this.sectionId = null
        this.dialogFormVisible = false     
      }).catch(() => {});
    },    
    getInfoLabels(title) {
      getInfoLabels({labelName:title}).then(response => {
        const { code, data } = response
        if (code == 0) {
          this.labels = data;
        }
      })
    },
    getSectionCascade() {
      getSectionCascade().then(response => {
        const { code, data } = response
        if (code == 0) {
          this.sections = data;
        }
      })
    },
    getSortList(filed){
      let { prop, order } = filed
      let { listQuery } = this
      listQuery['sortField'] = prop
      if(prop){
        listQuery['sortWay'] = order == 'descending' ? 'DESC' : 'ASC'
      }else{
        listQuery['sortWay'] = null
      }
      this.listQuery = listQuery
      this.getList()
    },
    handleUploadSuccess(rst, file, fileList) {
      const { code, data: { picUrlList } } = rst
      const { temp } = this
      if (code == 0) {
        temp['cover'] = picUrlList[0]
        this.temp = temp
        this.fileList = [{ name: file.url, url: file.url }]
      }
    },     
    handlePreview(file) {},
    handleRemove(file, fileList) {
      this.temp['cover'] = '';
      this.temp['file'] = [];
    },
    getList() {
      this.listLoading = true;
      let params = this.listQuery;
      const { date } = this;
      if (date) {
        params['beginTime'] = date[0];
        params['endTime'] = date[1];
      } else {
        delete params.beginTime;
        delete params.endTime;
      }
      getList(params).then(response => {
        const { code, data: { total, list } } = response;
        if (code == 0) {
          this.total = total
          this.list = list
          this.listLoading = false
        }
      });
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val
      this.getList()
    },
    handleModifyStatus(row) {
      const params = row.id
      getId(params).then(response => {    
        let { code, data } = response;
        this.temp = data
        this.sectionId = [this.temp.sectionId]
        this.labelsVal = this.temp.labels
        this.fileList = [{ name: this.temp.cover, url: this.temp.cover }]
        this.dialogFormVisible = true
      })
    },    
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          let { temp, temp:{content} } = this;
          temp['sectionId'] = this.sectionId[0]
          temp['labels'] = []
          this.labelsVal.forEach(element => {
            temp['labels'].push(element.id)
          });
          if(content.trim().length == 0 || content == '<p><br data-mce-bogus="1"></p>' || content  == '<p>&nbsp;</p>' || content == '<p><br></p>'){
              this.$message({
                message: '内容不能为空',
                type: 'error',
                duration: 1000
              });
              this.loading = false;
              return;
          }
          update(temp).then(response => {
            let { code } = response
            if (code == 0) {
              this.getList();
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            }
          }).catch(err =>{})
        }
      })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.app-container {
  padding: 20px;
}
.pagination-container {
  margin-top: 30px;
}
</style>